<template>
  <div>
    <div>
      <div>
        <el-button v-if="type===1" type="primary" @click="addGoodsShow = true">添加商品</el-button>
        <el-button v-if="type===1" type="primary" @click="delChoose()">批量删除</el-button>
        <el-button v-if="type===1" type="primary" @click="saveChoose()">批量保存</el-button>
      </div>
      <el-dialog
        title="添加关联商品"
        :visible.sync="addGoodsShow"
        append-to-body
      >
        <j-goods
          :add-goods-show01="addGoodsShow"
          :customer-type="customerType"
          :customer-id="customerId"
          :type="3"
          :scope="2"
          @addGoods="addGoodsThis"
        />
      </el-dialog>
      <!-- 搜索 -->
      <el-form label-width="100px" style="margin-bottom: 20px" size="small">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="关键字">
              <el-input v-model="query.keyword" placeholder="输入关键字搜索" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品类型">
              <zSelect :value.sync="query.goodsTagIds" url="api/dropDown/basGoodsTagList" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品分类">
              <treeselect
                v-model="curGoodsTypeList"
                :options="typeList"
                placeholder="选择商品分类"
                style="width: 100%"
                multiple
                @input="(val) => getNoStr(val, 'typeList', 'goodsTypeIds')"
                :normalizer="normalizer"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品品牌">
              <zSelect :value.sync="query.goodsBrandIds" url="api/dropDown/basGoodsBrandList" style="width:  100%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-table
        ref="goodsTable"
        :data="goodsList"
        style="width: 100%"
        border
        :row-style="rowClass"
        :row-class-name="tableRowClassName"
        height="500"
        @row-click="selectRow"
      >
        <el-table-column type="selection" width="60" />
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column
          prop="goodsCode"
          label="商品编码"
        />
        <el-table-column
          prop="goodsName"
          label="商品名称"
        />
        <el-table-column
          prop="barcode"
          label="条形码"
        />
        <el-table-column
          prop="fcustomerName"
          label="所属商贸公司"
        >
        <template slot-scope="scope">
          <span v-if="customerType !== 3">{{ scope.row.fcustomerName }}</span>
              <zSelect  v-if="customerType === 3"
              :label-key="'fcustomerName'"
              :value-key="'fcustomerId'"
              :value.sync="scope.row.fcustomerId"
              :show-name="scope.row.fcustomerName"
              url="api/dropDown/basCustomerGoodsBindFCustomerList"
              :params="{customerId: scope.row.customerId,goodsId: scope.row.goodsId}"
              style="width:  370px;"
              @getChange="changefcustomer"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="scustomerName"
          label="所属二批代理"
        >
          <template slot-scope="scope">
            <span v-if="customerType === 2">{{ scope.row.scustomerName }}</span>
            <zSelect
              v-if="customerType === 1"
              :label-key="'scustomerName'"
              :value-key="'scustomerId'"
              :value.sync="scope.row.scustomerId"
              :show-name="scope.row.scustomerName"
              url="api/dropDown/basCustomerGoodsBindSCustomerList"
              :params="{customerId: scope.row.customerId,goodsId: scope.row.goodsId}"
              style="width:  370px;"
              @getChange="changeScustomer"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="type === 1"
          prop="isAllowSale"
          label="是否销售"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.isAllowSale"
            >
              <el-option
                :key="0"
                label="否"
                :value="0"
              />
              <el-option
                :key="1"
                label="是"
                :value="1"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column v-if="type === 1" label="操作" width="180">
          <template slot-scope="scope">
            <el-button @click="saveGoods(scope.$index)">保存</el-button>
            <el-button @click="delGoods(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="scope === 3"
          prop="unGiftBoxCount"
          label="可下箱数"
        />
        <el-table-column
          v-if="scope === 3"
          prop="unGiftMainNum"
          label="可下零数"
        />
        <el-table-column
          v-if="scope === 3"
          prop="unGiftGoodsCount"
          label="可下数量"
        />
        <el-table-column
          v-if="scope === 3"
          prop="boxNum"
          label="下单箱数"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.boxNum"
              maxlength="12"
              style="width: 100%;float: left"
              @change="computedCount(scope.row,'boxNum')"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="scope === 3"
          prop="mainNum"
          label="下单零数"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.mainNum"
              maxlength="12"
              style="width: 100%;float: left"
              @change="computedCount(scope.row,'mainNum')"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="scope === 3"
          prop="goodsCount"
          label="下单数量"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.goodsCount"
              maxlength="12"
              style="width: 100%;float: left"
              @change="computedCount(scope.row,'goodsCount')"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="scope === 3"
          width="300px"
          prop="remark"
          label="备注"
        />
      </el-table>
      <el-pagination
        :current-page.sync="query.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
      />
      <div style="width: 100%;height: 50px">
        <el-button style="position:absolute;right:20px;bottom: 20px" type="primary" @click="addGoods">确认</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { crud } from '@crud/crud'
import { getGoods } from '@/api/erp/basGoods'
import Treeselect from '@riophae/vue-treeselect'
import { getTypeList } from '../../api/erp/basGoodsType'
import {
  getBasCustomerGoodsList,
  addOrSaveBasCustomerGoods,
  delOrSaveBasCustomerGoods,
  batchRemoveCustomerGoods,
  batchUpdateBasCustomerGoods,
  updateBasCustomerGoods
} from '@/api/erp/basCustomer'
import {
  getCustomerUnBindGoodsList,
  getfCustomerUnBindGoodsList,
  getsCustomerUnBindGoodsList
} from '@/api/erp/basCustomer'

export default {
  mixins: [crud()],
  name: 'JGoods',
  dicts: ['t_sales_gift_list_gift_type'],
  components: { Treeselect },
  props: {
    customerId: [String, Number],
    scope: {
      type: Number,
      default: 3
    },
    // type 0正常商品 1客户关联商品
    type: {
      type: Number,
      default: 0
    },
    customerType: {
      type: [Number, String],
      default: 0
    },
    dialogGoods: {
      type: Boolean,
      default: false
    },
    addGoodsShow01: {
      type: Boolean,
      default: false
    },
    toActivityShow: {
      type: Boolean,
      default: false
    },
    parentData: {
      type: Object,
      default: []
    }
  },
  data() {
    return {
      selections: [],
      query: {
        page: 1,
        size: 10,
        keyword: '',
        goodsTagIds: null,
        goodsTypeIds: null,
        goodsBrandIds: null,
        isIgnoreZeroUnGiftGoodsCount: 1
      },
      curGoodsTypeList:[],
      goodsList: [],
      total: 0,
      typeList: [],
      addGoodsShow: false
    }
  },
  watch: {
    dialogGoods(n) {
      if (n) {
        this.onGet()
      }
    },
    addGoodsShow01(n) {
      if (n) {
        this.onGet()
      }
    },
    toActivityShow(n) {
      if (n) {
        this.onGet()
      }
    },
    query: {
      handler(n, o) {
        this.onGet()
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    // this.onGet()
    this.getTypeList()
  },
  methods: {
    changeScustomer(e) {
      this.$set(this, 'sCustomerId', e.sCustomerId)
      this.scustomerId = e.scustomerId
      this.scustomerCode = e.scustomerCode
      this.scustomerName = e.scustomerName
      // console.log(this.scustomerCode, this.scustomerName, this.scustomerId)
      // console.log(e.scustomerCode, e.scustomerName, e.scustomerId)
    },
    changefcustomer(e) {
      this.$set(this, 'fCustomerId', e.fCustomerId)
      this.fcustomerId = e.fcustomerId
      this.fcustomerCode = e.fcustomerCode
      this.fcustomerName = e.fcustomerName
    },
    delChoose() {
      const goodsIdList = this.$refs.goodsTable.selection.map(item => item.goodsId)
      const datas = this.$refs.goodsTable.selection
      console.log(datas)
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(goodsIdList)
        batchRemoveCustomerGoods({ goodsIdList, customerId: this.customerId }).then(res => {
          this.$alert(res.msg, '提示')
          this.onGet()
        })
      }).catch(() => {
      })
    },
    saveChoose() {
      const list = this.goodsList.map(item => {
        return {
          goodsId: item.goodsId,
          customerId: item.customerId,
          isAllowSale: item.isAllowSale,
          fcustomerId: item.fcustomerId,
          scustomerId: item.scustomerId
        }
      })
      batchUpdateBasCustomerGoods({ list: list }).then(res => {
        this.$alert(res.msg, '提示')
        this.onGet()
      })
    },
    init() {
      this.query.page = 1
    },
    getTreeName(treeList, id) {
      let _this = this;
      for (let i = 0; i < treeList.length; i++) {
        let treeItem = treeList[i];
        if (treeItem.id === id) {
          return treeItem;
        } else {
          if (treeItem.children && treeItem.children.length > 0) {
            let res = _this.getTreeName(treeItem.children, id);
            if (res) {
              return res;
            }
          }
        }
      }
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },
    getNoStr(val, type, prop) {
      let str = "";
      val.forEach((item) => {
        const itemNode = this.getTreeName(this[type], item);
        str = this.getNode(itemNode, str);
      });
      this.query[prop] = str
    },
    getTypeList() {
      getTypeList({ page: 0, size: 999 }).then(res => {
        this.typeList = res
      })
    },
    normalizer(node) {
      // 去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    rowClass({ row, rowIndex }) {
      const selectedIndex = []
      this.$refs.goodsTable.selection.forEach(item => {
        selectedIndex.push(item.index)
      })
      if (selectedIndex.indexOf(rowIndex) >= 0) {
        return {
          'border': 'solid 1px #3dffef',
          'background-color': '#00ffff',
          'height': '10px'
        }
      } else {
        return {
          'height': '10px'
        }
      }
    },
    addGoods() {
      if (this.type === 1) {
        this.$emit('addGoods', this.goodsList)
        return
      }
      this.$emit('addGoods', this.$refs.goodsTable.selection)
    },
    addGoodsThis(val) {
      const data = val.map(item => {
        return {
          goodsId: item.goodsId,
          customerId: this.customerId,
          isAllowSale: 1,
          fcustomerId: item.fcustomerId,
          scustomerId: item.scustomerId
        }
      })
      addOrSaveBasCustomerGoods({ list: data }).then(res => {
        this.$alert(res.msg, '提示')
        this.addGoodsShow = false
        this.onGet()
      })
    },
    delGoods(index) {
      this.$confirm('此操作将删除该商品, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        delOrSaveBasCustomerGoods({ ...this.goodsList[index], customerId: this.customerId }).then(res => {
          this.$alert(res.msg, '提示')
          this.onGet()
        })
      })
    },
    saveGoods(index) {
      this.$confirm('此操作将修改该商品, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        updateBasCustomerGoods({ ...this.goodsList[index], customerId: this.customerId }).then(res => {
          this.$alert(res.msg, '提示')
          this.onGet()
        })
      })
    },
    onGet() {
      if (!this.customerId) {
        return
      }
      const keyWord = this.query.keyword
      if (this.type === 1) {
        getBasCustomerGoodsList({ ...this.query, customerId: this.customerId }).then(res => {
          if (keyWord !== this.query.keyword) return
          this.goodsList = res.data.content
          this.total = res.data.totalElements
        })
        return
      } else if (this.type === 3) {
        if (this.customerType === 1) {
          if (keyWord !== this.query.keyword) return
          getCustomerUnBindGoodsList({ ...this.query, customerIds: this.customerId }).then(res => {
            this.goodsList = res.content
          })
        } else if (this.customerType === 2) {
          if (keyWord !== this.query.keyword) return
          getfCustomerUnBindGoodsList({ ...this.query, fCustomerIds: this.customerId }).then(res => {
            this.goodsList = res.content
          })
        } else if (this.customerType === 3) {
          if (keyWord !== this.query.keyword) return
          getsCustomerUnBindGoodsList({ ...this.query, sCustomerIds: this.customerId }).then(res => {
            this.goodsList = res.content
          })
        }
        // getGoods(this.query).then(res=>{
        //   this.goodsList = res.content
        //   this.total = res.totalElements
        // })
      }
      // 活动商品接口
      this.goodsList = []
      getGoods({ ...this.query, customerId: this.customerId, scope: this.scope, size: 999 }).then(res => {
        this.goodsList = res.content
        this.total = res.totalElements
        this.$forceUpdate()
      })
    },
    handleSizeChange(val) {
      this.query.size = val
    },
    handleCurrentChange(val) {
      this.query.page = val
    },
    selectRow(row, column, event) {
      this.$refs['goodsTable'].toggleRowSelection(row)
      this.selection = this.$refs['goodsTable'].toggleRowSelection(row)
    },
    computedCount(row, type) {
      if (type === 'boxNum') {
        row.goodsCount = Number(row.boxNum) * Number(row.boxUnitCount) + Number(row.mainNum)
      } else if (type === 'mainNum') {
        if (Number(row.mainNum) > Number(row.boxUnitCount)) {
          row.boxNum = Number(row.boxNum) + parseInt(Number(row.boxUnitCount) / Number(row.mainNum))
        }
        row.goodsCount = Number(row.boxNum) * Number(row.boxUnitCount) + Number(row.mainNum)
      } else if (type === 'goodsCount') {
        console.log(Number(row.goodsCount) / Number(row.boxUnitCount))
        row.boxNum = parseInt(Number(row.goodsCount) / Number(row.boxUnitCount))
        row.mainNum = Number(row.goodsCount) % Number(row.boxUnitCount)
        if (isNaN(row.mainNum)) {
          row.mainNum = 0
        }
      }
      if (row.goodsCount > row.unGiftGoodsCount) {
        this.$message({
          message: '下单数量不可大于可下单数量',
          type: 'error'
        })
        row.boxNum = 0
        row.mainNum = 0
        row.goodsCount = 0
      }
    }
  }
}
</script>

<style scoped>

</style>
